package com.ezgo.erc.utils;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ezgo.erc.entity.Sysuser;
import com.ezgo.erc.master.utils.SpringContext;
import com.ezgo.erc.service.CacheService;
import com.ezgo.erc.service.SysuserService;

public class UserUtil {

	public static CacheService cacheService = SpringContext.getBean(CacheService.class);
	public static SysuserService sysuserService = SpringContext.getBean(SysuserService.class);
	public static final String CACHE_USER = "loginUser";

	/**
	 * 
	 * TODO(获取登录用户信息)
	 *
	 * @return Sysuser
	 */
	public static Sysuser getUser() {
		Sysuser user = null;
		if (cacheService.exists(CACHE_USER)) {
			user = JSON.parseObject(cacheService.get(CACHE_USER), Sysuser.class);
		}
		return user;
	}

	/**
	 * 
	 * TODO(登陆用户验证)
	 *
	 * @param username
	 *            用户名
	 * @param password
	 *            用户密码
	 * @return Sysuser 返回用户对象
	 */
	public static Sysuser getUser(Map<String, Object> map) {
		Sysuser user = null;
		List<Sysuser> userList = sysuserService.getSysuserList(map);
		if (userList != null && userList.size() > 0) {
			user = userList.get(0);
			cacheService.set(CACHE_USER, JSON.toJSONString(user), 7200);
		}
		return user;
	}

	/**
	 * 
	 * TODO(用户退出，清除缓存)
	 * 
	 */
	public static void userLogout() {
		if (cacheService.exists(CACHE_USER)) {
			cacheService.del(CACHE_USER);
		}
	}

	/**
	 * 
	 * TODO(累计登陆失败次数)
	 *
	 * @param cacheStr
	 *            缓存标识
	 * @param failCount
	 *            初始失败次数
	 * @param isPlusOrClean
	 *            是否累计或清零 累计、清零
	 * @return int 返回累计结果
	 */
	public static int calcLoginFail(String cacheStr, int failCount, boolean isPlusOrClean) {
		if (failCount == 0 && isPlusOrClean) {
			if (cacheService.exists(cacheStr)) {
				failCount = Integer.parseInt(cacheService.get(cacheStr)) + 1;
				cacheService.set(cacheStr, failCount + "");
				return failCount;
			} else {
				failCount += 1;
				cacheService.set(cacheStr, failCount + "");
			}
		}
		if (failCount == 0 && !isPlusOrClean) {
			if (cacheService.exists(cacheStr)) {
				cacheService.del(cacheStr);
			}
		}
		return failCount;
	}

}
